import { generateToken } from '../utils/jwt';
import { SQL_QUERIES } from '../sql/sql';

export const handleScanClient = {
  // 登录处理
  async login(request, env) {
    try {
      const { code, clientType = 'wechat' } = await request.json();
      
      let userInfo;
      switch (clientType) {
        case 'wechat':
          userInfo = await handleWechatLogin(code, env);
          break;
        case 'douyin':
          userInfo = await handleDouyinLogin(code, env);
          break;
        case 'app':
          userInfo = await handleAppLogin(code, env);
          break;
        default:
          throw new Error('Unsupported client type');
      }

      if (!userInfo) {
        return new Response(JSON.stringify({
          code: 401,
          message: 'Login failed'
        }));
      }

      // 生成 token
      const token = await generateToken({
        userId: userInfo.userId,
        clientType,
        ...userInfo
      }, env.jwtSecretLoginAPP, '1h');

      const refreshToken = await generateToken({
        userId: userInfo.userId,
        clientType,
        ...userInfo
      }, env.jwtSecretLoginAPP, '7d');

      return new Response(JSON.stringify({
        code: 200,
        data: {
          token,
          refreshToken,
          userInfo
        }
      }));
    } catch (error) {
      console.error('Login error:', error);
      return new Response(JSON.stringify({
        code: 500,
        message: error.message || 'Internal server error'
      }));
    }
  }
};

// 微信登录处理
async function handleWechatLogin(code, env) {
  try {
    // 调用微信接口获取openid和session_key
    const response = await fetch(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${env.WX_APPID}&secret=${env.WX_SECRET}&js_code=${code}&grant_type=authorization_code`
    );
    const data = await response.json();
    
    if (!data.openid) {
      throw new Error('Failed to get openid');
    }

    // 检查账号是否存在
    const result = await env.DB.prepare(
      { ...SQL_QUERIES.checkExists, requireAuth: false }.sql
        .replace('??', 'accounts')  // 表名
        .replace('??', 'openid')    // 字段名
    ).bind(data.openid).first();

    return {
      platform: 'wechat',
      isHasAccount: result.exists === 1  // SQLite 返回 1 表示存在，0 表示不存在
    };
  } catch (error) {
    console.error('WeChat login error:', error);
    return null;
  }
}

// 抖音登录处理
async function handleDouyinLogin(code, env) {
  // TODO: 实现抖音登录逻辑
  throw new Error('Douyin login not implemented');
}

// APP登录处理
async function handleAppLogin(code, env) {
  // TODO: 实现APP登录逻辑
  throw new Error('App login not implemented');
}
